<?php

App::uses('AppController', 'Controller');

class UsersController extends AppController {

	var $name = 'Users';

	var $allowActions = array( 'login', 'logout' );
	var $components = array( 'Crypter' );

	var $uses = array('User');


	/**
	 * List user
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_index() {

		$als = 'User';

		$status = array(
			4 => 'Đang hoạt động',
			5 => 'Đã khóa',
			9 => 'Đã xóa'
		);

		// Get Company
		App::uses('Company', 'Model');
		$Company = new Company();

		// Get Role
		App::uses('Role', 'Model');
		$Role = new Role();

		$this->set('roles', $Role->getList());
		$this->set('companies', $Company->getList());
		$this->set('liststatus', $status);
		$this->set('users', $this->User->getAll());
	}

	/**
	 * Add
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_add($id = null)
	{
		if(!empty($this->request->data))
		{
			$data = &$this->request->data['User'];

			// Kiem tra upload avatar
			if(!empty($data['avatar']['name']) && $data['avatar']['error'] == 0) {
				$data['avatar'] = $this->_upload($data['avatar']);

				if(isset($data['oldavatar']) ) {
					$path1 = PUBLIC_IMAGE_DETAIL.$data['oldavatar'];
					$path2 = PUBLIC_DETAIL_SHOW.$data['oldavatar'];
					@unlink($path1);
					@unlink($path2);
				}
			} else {
				$data['avatar'] = isset($data['oldavatar']) ? $data['oldavatar'] : '';
			}

			// Convert company
			if( !empty( $data['company_id'] )) {
				$data['company_id'] = implode(',', $data['company_id']);
			}

			// Kiem tra password cu
			$oldpass = false;
			if( empty( $data['password'] )) {
				if(!empty($data['oldpass'])) {
					$data['password'] = $data['oldpass'];
					$oldpass = true;
				} else {
					$this->User->validationErrors['password'] = array('Password not empty.');
				}
			}

			// Kiem tra errors
			$this->User->set($data);
			$errors = $this->User->invalidFields();

			//Save
			if(empty($errors)) {
				// Kiem tra password
				if(!$oldpass)
					$data['password'] = $this->Auth->password($data['password']);

				// kiem tra edit
				if( empty($data['id']) ) {
					unset($data['id']);
				}

				$this->Common->get_common_info($data);

				if($this->User->save($data, false)) {
					$this->Session->setFlash('Save user success.', 'success');
					$this->redirect('/admin/users');
				} else {
					$this->Session->setFlash('Save user fail.', 'error');
				}
			} else {
				// Convert company
				if( !empty( $data['company_id'] )) {
					$data['company_id'] = explode(',', $data['company_id']);
				}

				$this->Session->setFlash('Save user fail.', 'error');
			}
		}

		// Truong hop show edit
		if( !empty( $id )) {
			$info = $this->User->getInfoById($id);

			if(!empty($info)) {
				$info['User']['company_id'] = explode( ',', $info['User']['company_id']);
				$info['User']['oldpass'] = $info['User']['password'];
				$info['User']['password'] = '';
				$this->request->data = $info;
			}
		}

		// Get Company
		App::uses('Company', 'Model');
		$Company = new Company();
		// Get Role
		App::uses('Role', 'Model');
		$Role = new Role();

		$this->set('roles', $Role->getList());
		$this->set('companies', $Company->getList());
	}



	/**
     * Login
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function admin_login($usernameregis = '', $passwordregis = '')
    {
    	$this->layout = 'login';
        $u = $this->Auth->user();

        if( !empty($u ) )
        {
            $this->redirect('/admin');
        }

        if( !empty($_GET['denied']) && $_GET['denied'] == 1 )
            $this->Session->setFlash( __('Bạn không được phép truy cập vào các chức năng hệ thống.', 'error'));

        //--------------------------------------------------------------------//
        // Check login info
        //--------------------------------------------------------------------//
        if( !empty( $this->request->data ) )
        {
            // update password
            $this->request->data['User']['password'] =
                $this->Auth->password( $this->request->data['User']['password'] );
//pr($this->request->data['User']['password']);
//exit;
            $user  = $this->User->validateLogin($this->request->data);

            if (!empty( $user ) )
            {
                // create full name
                $this->Auth->login($user['User']);

                // create security string
                $this->Session->write('security_key', $this->Crypter->alphaID( strtotime(date("Y-m-d H:i:s")) ) );

                // save current user id
                $this->Session->write(CURRENT_USER_ID,$user['User']['id']);

                App::uses( 'Company', 'Model' );
                $Company = new Company( );

                $cond = array('status' => 4 );

                // Kiem tra neu khac admin or thu quy thi lay company cua user do
                $com = $this->Auth->user('company_id');
                if(  !in_array( $this->Auth->user('role'), array( 1, 2 ) ) )
                {
                	if(!empty( $com )) {
	                    $com = explode(',', $com);
                	}

                	$cond['id'] =  $com ;
                }

                $company = $Company->find( 'list', array(
                    'conditions' => $cond,
                    'fields' => array( 'id', 'name' ) ) );

				// neu ko co company thi ko cho dang nhap vao
                if(empty($company))
                {
                	$this->redirect('/admin/logout/?denied=1');
                }

                $this->Session->write( 'company_list', $company );

                // set current company
                $keys = array_keys($company);
                $comp_id = $keys[0];

                $comp = $Company->read( array( 'id', 'name', 'address', 'hotline', 'phone', 'website', 'logo' ),  $comp_id );
                $comp = $comp['Company'];
                $this->Session->write( 'current_company', $comp );


                if( !empty($user ) )
                {
                    $this->redirect('/admin');
                }
            }
            else
            {
                $this->request->data['User']['password'] = "";
                $this->Session->setFlash( __('Đăng nhập thất bại. Xin kiểm tra lại thông tin đăng nhập.'));
             }
        }

    }

	/**
     * Logout
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function admin_logout()
    {
       // $this->AuthExtension->logout();
        $this->Session->destroy();
        if( !empty($_GET['denied']) && $_GET['denied'] == 1 )
            $this->redirect( "/admin/users/login/?denied=1" );
        else
            $this->redirect( "/admin/users/login" );
    }
}
